package ThreadDemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 线程池
 */
public class ThreadDemo14 {
    static class Worker extends Thread{
        BlockingQueue <Runnable>queue=null;
        public Worker(BlockingQueue queue) {
            this.queue=queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Runnable command = queue.take();
                    command.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //创建一个线程池
    static class MY_ThreadPoor{
        //用一个阻塞队列来记录执行顺序
        private BlockingQueue<Runnable> queue=new LinkedBlockingQueue<>();
        //用来当作存放线程的地方
        private List<Thread>list=new ArrayList<>();
        //用来限制线程的多少
        private static final int MAX_Thread_Number=10;
        //用来存放和创建线程
        public void submit(Runnable command) throws InterruptedException {
            if(list.size()<MAX_Thread_Number){
                Thread t=new Worker(queue);
                t.start();
                list.add(t);
            }
            queue.put(command);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MY_ThreadPoor poor=new MY_ThreadPoor();
        for (int i = 0; i < 100; i++) {
            poor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hehe");
                }
            });
        };
    }
}
